package com.example.xmpic.ui.adapter;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.xmpic.R;
import com.example.xmpic.R2;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author skygge
 * @date 2020/7/6.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class WeekAdapter<T> extends RecyclerView.Adapter<WeekAdapter.ItemHolder> {

    private Context mContext;
    private List<T> mList;

    public WeekAdapter(Context mContext, List<T> mList) {
        this.mContext = mContext;
        this.mList = mList;
    }

    public List<T> getList() {
        return mList;
    }

    public int getWeekMask(){
        int mWeekMask = 0;
        for (int i = 0; i < mList.size(); i++) {
            boolean isSelected = ((Bundle) mList.get(i)).getBoolean("selected", false);
            if (isSelected) {
                mWeekMask |= (int) Math.pow(2, i);
            }
        }
        return mWeekMask;
    }

    @NonNull
    @Override
    public ItemHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_week_time, viewGroup, false);
        return new ItemHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ItemHolder itemHolder, int i) {
        Bundle data = (Bundle) mList.get(i);
        boolean isSelected = data.getBoolean("selected", false);
        itemHolder.weekItem.setText(data.getString("name"));
        itemHolder.weekBg.setBackgroundResource(isSelected ? R.drawable.btn_click_bg : R.drawable.btn_normal_bg);
        itemHolder.weekItem.setTextColor(isSelected ? ContextCompat.getColor(mContext, R.color.white)
                : ContextCompat.getColor(mContext, R.color.text_title));
        itemHolder.itemView.setOnClickListener(v -> {
            ((Bundle) mList.get(i)).putBoolean("selected", !isSelected);
            notifyItemChanged(i);
        });
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    static class ItemHolder extends RecyclerView.ViewHolder {
        @BindView(R2.id.week_item)
        TextView weekItem;
        @BindView(R2.id.week_bg)
        RelativeLayout weekBg;
        public ItemHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
